package org.xiaobai.ai.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.xiaobai.ai.entity.ChatRoomShareVO;
import org.xiaobai.ai.entity.ChatRoomVO;
import org.xiaobai.ai.mapper.ChatRoomShareMapper;
import org.xiaobai.ai.request.RoomShareAddRequest;
import org.xiaobai.ai.service.ChatRoomService;
import org.xiaobai.ai.service.ChatRoomShareService;
import org.xiaobai.common.utils.UserUtil;
import org.xiaobai.core.exception.TipException;
import org.xiaobai.core.utils.DateTimeUtil;
import org.xiaobai.core.utils.RandomPwdUtil;

import javax.annotation.Resource;
import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class ChatRoomShareServiceImpl extends ServiceImpl<ChatRoomShareMapper, ChatRoomShareVO> implements ChatRoomShareService {

    @Value("${room.shareUrl}")
    private String shareUrl;

    @Lazy
    @Resource
    private ChatRoomService chatRoomService;

    @Override
    public String addShare(RoomShareAddRequest addRequest) {
        ChatRoomVO roomVO = chatRoomService.getById(addRequest.getRoomId());
        if (Objects.isNull(roomVO)) {
            throw new TipException("房间信息不存在");
        }
        String randomString = RandomUtil.randomString(10);
        ChatRoomShareVO share = new ChatRoomShareVO();
        share.setValidDate(addRequest.getValidDate() == null ? DateTimeUtil.parseDate("9999-12-31 00:00:00") : addRequest.getValidDate());
        share.setShareFrom(UserUtil.getUserId());
        share.setShardCode(randomString);
        share.setRoomId(addRequest.getRoomId());
        save(share);
        return shareUrl + randomString;
    }

    @Override
    public Long invite(String code) {
        ChatRoomShareVO roomShare = getOne(new LambdaQueryWrapper<ChatRoomShareVO>()
                .eq(ChatRoomShareVO::getShardCode, code));
        if (Objects.isNull(roomShare)) {
            throw new TipException("分享码有误");
        }
        Long userId = UserUtil.getUserId();

        ChatRoomVO roomVO = chatRoomService.getById(roomShare.getRoomId());
        if (Objects.isNull(roomVO)) {
            throw new TipException("房间已被删除");
        }
        // 防止嵌套分享到用户自己，遇到房间创建人是自己，直接返回
        if (Objects.equals(roomVO.getUserId(), UserUtil.getUserId())) {
            return roomShare.getRoomId();
        }
        if (!roomShare.getValid()) {
            // 如果已经被邀请了，返回
            if (userId.equals(roomShare.getShareTo())) {
                return roomShare.getRoomId();
            }
            throw new TipException("分享码失效了");
        }
        if (roomShare.getShareFrom().equals(userId)) {
            return roomShare.getRoomId();
        }
        roomShare.setShareTo(userId);
        roomShare.setValid(false);
        updateById(roomShare);
        return roomShare.getRoomId();
    }

    @Override
    public List<ChatRoomShareVO> findUserByFromUser(Long from) {
        return list(new LambdaQueryWrapper<ChatRoomShareVO>()
        .eq(ChatRoomShareVO::getShareFrom, from)
        .eq(ChatRoomShareVO::getValid, false)
        .ge(ChatRoomShareVO::getValidDate, new Date()));
    }

    @Override
    public List<ChatRoomShareVO> findUserByToUser(Long to) {
        return list(new LambdaQueryWrapper<ChatRoomShareVO>()
                .eq(ChatRoomShareVO::getShareTo, to)
                .eq(ChatRoomShareVO::getValid, false)
                .ge(ChatRoomShareVO::getValidDate, new Date()));
    }

    @Override
    public Boolean removeByUserId(Long userId) {
        return remove(new LambdaQueryWrapper<ChatRoomShareVO>()
        .eq(ChatRoomShareVO::getShareTo, userId));
    }

    @Override
    public Boolean removeByUserIdAndRoomId(Long userId, Long roomId) {
        return remove(new LambdaQueryWrapper<ChatRoomShareVO>()
                .eq(ChatRoomShareVO::getShareTo, userId)
        .eq(ChatRoomShareVO::getRoomId, roomId));
    }
}
